package client_heartbeat

import (
	"fmt"
	"github.com/zhongshaofa/swan-jobs/internal/models"
	"github.com/zhongshaofa/swan-jobs/internal/repositorys"
	rpcClient "github.com/zhongshaofa/swan-jobs/internal/rpc/client"
	rpcProtoClient "github.com/zhongshaofa/swan-jobs/internal/rpc/proto/client"
	"strconv"
	"time"
)

func CheckHeartbeat() {
	fmt.Println("CheckHeartbeat:检测客户端健康情况")

	repository := repositorys.ClientInterface(repositorys.ClientRepository{})
	whereClient := models.Client{Status: models.StatusEnable}

	for true {
		time.Sleep(5 * 1e9)

		clientList, err := repository.GetClientList(&whereClient)

		if err != nil {
			fmt.Println("CheckHeartbeat GetClientList：", err)
			continue
		}

		for _, client := range clientList {
			if len(client.Ip) == 0 || client.Port == 0 {
				continue
			}
			go send(client, repository)
		}
	}

}

func InitClientHeartbeat() {
	repository := repositorys.ClientInterface(repositorys.ClientRepository{})
	whereClient := models.Client{Status: models.StatusEnable}

	clientList, err := repository.GetClientList(&whereClient)

	if err != nil {
		fmt.Println("InitClientHeartbeat GetClientList：", err)
		return
	}

	for _, client := range clientList {
		if len(client.Ip) == 0 || client.Port == 0 {
			continue
		}
		send(client, repository)
	}
}

func send(client *models.Client, repository repositorys.ClientInterface) {
	connectAddress := client.Ip + ":" + strconv.Itoa(client.Port)
	request := rpcProtoClient.HeartbeatRequest{ClientId: int32(client.ID)}
	heartbeatResponse, err := rpcClient.HeartbeatByScheduler(connectAddress, &request)

	if err != nil {
		client.CpuPercent = 0
		client.MemoryPercent = 0
		client.IsHeartbeat = models.False
		client.CheckHeartbeatAt = time.Now()
	} else {
		client.CpuPercent = int(heartbeatResponse.CpuPercent)
		client.MemoryPercent = int(heartbeatResponse.MemoryPercent)
		client.IsHeartbeat = models.True
		client.CheckHeartbeatAt = time.Now()
	}

	_ = repository.Heartbeat(client)
}
